# 构建阶段
FROM swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/node:18-alpine AS builder

WORKDIR /app

# 配置华为云镜像源（可选，加速 apk 安装）
RUN sed -i 's@https://dl-cdn.alpinelinux.org@https://mirrors.huaweicloud.com@g' /etc/apk/repositories

# 安装依赖（仅当需要原生模块时才需 apk，Next.js 通常不需要）
# RUN apk add --no-cache python3 make g++

# 1. 先复制 package*.json，利用缓存
COPY package*.json ./

# 2. 安装依赖
RUN npm ci

# 3. 复制源码
COPY . .

# 4. 构建（确保 next.config.js 启用了 output: 'standalone'）
RUN npm run build

# 生产阶段
FROM swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/node:18-alpine AS runner

WORKDIR /app

ENV NODE_ENV=production

# 创建非 root 用户
RUN addgroup -g 1001 -S nodejs && \
    adduser -S nextjs -u 1001

# 复制 standalone 输出
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public

# 设置权限
RUN chown -R nextjs:nodejs /app
USER nextjs

EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME=0.0.0.0

CMD ["node", "server.js"]